﻿using Confluent.Kafka;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Octokit;
using SharpCompress.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using WorkFlowCore.Common.Utils;
using static System.Net.WebRequestMethods;

namespace WorkFlowCore.Resources.GitResources
{
    public class GiteeResourceManager : IResourceManager
    {

        private string owner;
        private string repoName;
        private string branchName; // 或者你要提交到的其他分支
        private string token;
        private string fileSubfix = ".png";//防止被过滤，统一给文件加了个后缀


        public GiteeResourceManager(IOptions<GitResourceOptions> options)
        {
            owner = options.Value.Owner;
            repoName = options.Value.RepoName;
            branchName = options.Value.BranchName;
            token = options.Value.Token;
        }
        public async Task<byte[]> Download(string fileId)
        {
            try
            {
                var resource = await GetResourceInfo(fileId);
                return await Download(resource);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public async Task<byte[]> Download(ResourceInfo resource)
        {
            try
            {
                if (resource == null)
                {
                    return null;
                }
                //根据实际的文件信息下载文件
                var filePath = $"{resource.FullPath.Trim('/')}{fileSubfix}";

                var url = $"https://gitee.com/api/v5/repos/{owner}/{repoName}/contents/{filePath}?access_token={token}&ref={branchName}";

                using (var client = new HttpClient())
                {
                    var response = await client.GetAsync(url);

                    if (response.IsSuccessStatusCode)
                    {
                        var jsonResponse = await response.Content.ReadAsStringAsync();
                        var fileData = JsonConvert.DeserializeObject<GiteeFileResponse>(jsonResponse);

                        // Base64解码并保存到本地
                        var fileBytes = Convert.FromBase64String(fileData.Content);
                        return fileBytes;
                    }
                    else
                    {
                        Console.WriteLine($"文件下载失败：{response.StatusCode}, {await response.Content.ReadAsStringAsync()}");
                    }
                }
                return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public async Task<ResourceInfo> Upload(byte[] data, string fileName, string path)
        {
            //如果有重复的文件，就直接返回
            var fileId = Encrypt.MD5Encrypt32($"{path}/{fileName}");
            var resource = await GetResourceInfo(fileId);
            if (resource != null)
            {
                return resource;
            }

            //按源文件路径保存
            var realPath = await UploadFile(data, fileName, path);
            if (string.IsNullOrWhiteSpace(realPath))
            {
                return null;
            }

            //生产文件id并映射源文件路径
            resource = new ResourceInfo
            {
                FullPath = realPath,
                Name = fileName,
                Length = data.Length,
                Subfix = Path.GetExtension(fileName),
                Id = fileId,
            };

            var resourceContent = JsonConvert.SerializeObject(resource);
            await UploadFile(Encoding.UTF8.GetBytes(resourceContent), resource.Id.ToString(), "ResourceInfo");

            try
            {
                var localResourceInfoPath = Path.Combine(AppContext.BaseDirectory, "ResourceInfo");
                if (!Directory.Exists(localResourceInfoPath))
                {
                    Directory.CreateDirectory(localResourceInfoPath);
                }
                System.IO.File.WriteAllText(Path.Combine(localResourceInfoPath, fileId), resourceContent);
            }
            catch (Exception)
            {

            }

            return resource;
        }

        public async Task<ResourceInfo> GetResourceInfo(string fileId)
        {
            try
            {

                try
                {
                    var filePath = Path.Combine(AppContext.BaseDirectory, "ResourceInfo", fileId);
                    if (System.IO.File.Exists(filePath))
                    {
                        return JsonConvert.DeserializeObject<ResourceInfo>(System.IO.File.ReadAllText(filePath));
                    }
                }
                catch (Exception)
                {

                }


                //根据id 获取文件信息
                var idPath = $"ResourceInfo/{fileId}{fileSubfix}";


                var url = $"https://gitee.com/api/v5/repos/{owner}/{repoName}/contents/{idPath}?access_token={token}&ref={branchName}";

                using (var client = new HttpClient())
                {
                    var response = await client.GetAsync(url);

                    if (response.IsSuccessStatusCode)
                    {
                        var jsonResponse = await response.Content.ReadAsStringAsync();
                        var fileData = JsonConvert.DeserializeObject<GiteeFileResponse>(jsonResponse);

                        // Base64解码并保存到本地
                        var fileBytes = Convert.FromBase64String(fileData.Content);
                        var content = Encoding.UTF8.GetString(fileBytes);
                        Console.WriteLine("文件下载成功！");
                        var resource = JsonConvert.DeserializeObject<ResourceInfo>(content);
                        return resource;
                    }
                    else
                    {
                        Console.WriteLine($"文件下载失败：{response.StatusCode}, {await response.Content.ReadAsStringAsync()}");
                    }
                }

                return null;

            }
            catch (Exception ex)
            {
                return null;
            }
        }


        private async Task<string> UploadFile(byte[] data, string fileName, string path)
        {
            var commitMessage = "file upload test";
            var resultPath = $"{(string.IsNullOrWhiteSpace(path) ? "" : $"{path}/")}{HttpUtility.UrlEncode(fileName)}";
            var filePath = $"{resultPath}{fileSubfix}";

            var fileContent = Convert.ToBase64String(data);
            try
            {
                var url = $"https://gitee.com/api/v5/repos/{owner}/{repoName}/contents/{filePath}";

                using (var client = new HttpClient())
                {
                    var jsonContent = new
                    {
                        access_token = token,
                        content = fileContent,
                        message = commitMessage,
                        branch = branchName
                    };

                    var response = await client.PostAsync(
                        url,
                        new StringContent(System.Text.Json.JsonSerializer.Serialize(jsonContent), Encoding.UTF8, "application/json")
                    );

                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("文件上传成功！");
                        return resultPath;
                    }
                    else
                    {
                        Console.WriteLine($"文件上传失败：{response.StatusCode}, {await response.Content.ReadAsStringAsync()}");
                    }
                }

                return string.Empty;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.StackTrace);
                return string.Empty;
            }
        }
    }

    public class GiteeFileResponse
    {
        public string Content { get; set; }
    }
}
